#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2011-11-13
@author: shell.xu
'''
import os, sys, logging, marshal
import zmq
from beanstalkc import Connection as beanstalk_conn

def to_handler(handlers, msg):
    try:
        obj = marshal.loads(msg)
        cmd = handlers[obj[0]]
        params = u' '.join([unicode(i) for i in obj[1:]])
        logging.debug('message %s(%s) recved.' % (obj[0], params))
    except:
        logging.debug('a message recved but can\'t handle.')
        return True
    try:
        r = cmd(*obj[1:])
        logging.debug('message %s returned.' % unicode(r))
        return r
    except:
        logging.debug('message %s process failed.' % obj[0])
        return False

def btmqloop(handlers, tube = None):
    ''' beanstalk的服务器端队列，将任务发送到对应函数上 '''
    bt = beanstalk_conn(parse_yaml = False)
    if tube is not None: bt.using(tube)
    while True:
        job = bt.reserve(1)
        if job is None:
            if 'on_idle' in handlers: handlers['on_idle']()
            continue
        if to_handler(handlers, job.body):
            job.delete()
        else: job.release(delay = 10)

def zmqloop(handlers, addr):
    ''' zeromq的服务器端队列，将任务发送到对应函数上 '''
    zmqctx = zmq.Context()
    socket = zmqctx.socket(zmq.REP)
    socket.bind(addr)
    while True:
        msg = socket.recv()
        rslt = to_handler(handlers, msg)
        if not rslt: socket.send("")
        else: socket.send(marshal.dumps(rslt))
